public class Sort {
    public static void mergeSort(int[] array){
        mergeSortFunc(array,0,array.length - 1);
    }

    private static void mergeSortFunc(int[] array, int left, int right) {
        if(left == right){
            return;
        }
        int mid = (left + right) / 2;
        //分割
        mergeSortFunc(array, left, mid);
        mergeSortFunc(array, mid + 1,right);
        //合并
        combine(array,left,right,mid);
    }

    private static void combine(int[] array, int left, int right, int mid) {
        int s1 = left;
        int e1 = mid;
        int s2 = mid + 1;
        int e2 = right;
        int k = 0;
        int[] tmp = new int[right - left + 1];
        while(s1 <= e1 && s2 <= e2){
            if(array[s1] <= array[s2]){
                tmp[k++] = array[s1++];
            }else{
                tmp[k++] = array[s2++];
            }
        }
        while(s1 <= e1){
            tmp[k++] = array[s1++];
        }
        while(s2 <= e2){
            tmp[k++] = array[s2++];
        }
        //保证tmp中的元素都有序
        for (int i = 0; i < tmp.length; i++) {
            array[i + left] = tmp[i];
        }
    }

    /*
     * 归并排序(非递归版本)
     * */
    public static void mergeSort2(int[] array){
        int gap = 1;
        while(gap < array.length){
            for (int i = 0; i < array.length; i += gap) {
                int left = i;
                int mid = left + gap - 1;
                int right = gap + mid;
                if(mid >= array.length){
                    mid = array.length - 1;
                }
                if(right >= array.length){
                    right = array.length - 1;
                }
                combine(array,left,right,mid);
            }
            gap *= 2;
        }
    }

    /*
    * 计数数组
    * */

    public static void countSort(int[] array){
        int max = array[0];
        int min = array[0];
        for (int i = 1; i < array.length; i++) {
            if(max < array[i]){
                max = array[i];
            }
            if(min > array[i]){
                min = array[i];
            }
        }
        //创建一个计数数组，遍历数组，往里放
        int len = max - min + 1;
        int[] count = new int[len];
        for (int i = 0; i < array.length; i++) {
            int index = array[i] - min;
            count[index]++;
        }
        //遍历计数数组，拿出来放进去
        int arrIndex = 0;
        for (int i = 0; i < count.length; i++) {
            while(count[i] != 0){
                array[arrIndex] = i + min;
                arrIndex++;
                count[i]--;
            }
        }

    }

}
